package com.chtwm.pool;

import java.util.concurrent.*;

/**
 * 线程池使用固定参数配置
 *
 * @author Aimy
 * @createTime 2021/6/17 10:48
 **/
public class QbdPool {

    /**
     * 默认线程池大小为核数*2
     */
    private static Integer poolSize = Runtime.getRuntime().availableProcessors() * 2;

    /**
     * 存活时间
     */
    private final static Long timeAlive = 1000L * 10;

    /**
     * 阻塞队列长度
     */
    private final static Integer blockQueueLength = 100;

    /**
     * 持有执行器
     */
    private static class QbdPoolHolder {
        private static final ExecutorService executorService = new ThreadPoolExecutor(poolSize, poolSize,
                timeAlive, TimeUnit.MILLISECONDS
                , new LinkedBlockingQueue<>(blockQueueLength),
                r -> {
                    Thread t = new Thread(r);
                    t.setName("QbdPool-" + t.getName());
                    return t;
                });
    }


    private QbdPool() {
    }

    /**
     * 提交runable
     *
     * @param r
     * @param <R>
     * @return
     */
    public static <R> Future<R> submit(Runnable r) {
        return (Future<R>) QbdPoolHolder.executorService.submit(r);
    }

    /**
     * 提交带返回值的任务
     *
     * @param c
     * @param <R>
     * @return
     */
    public static <R> Future<R> submit(Callable<R> c) {
        return QbdPoolHolder.executorService.submit(c);
    }

    /**
     * 线程池大小
     *
     * @return
     */
    public static int getPoolSize() {
        return poolSize;
    }


}
